<?php

namespace App\Imports;

use App\Models\Department;
use App\Models\Dorm;
use App\Models\Staff;
use App\Models\StaffPosition;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;


class StaffImport implements ToModel, WithHeadingRow
{
    public $total = 0;
    public $success = 0;
    public $fail = 0;
    public $ignore = 0;

    public function __construct()
    {
        $this->total = 0;
        $this->success = 0;
        $this->fail = 0;
        $this->ignore = 0;
    }

    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function model(array $row)
    {
        try {
            $dept = Department::query()->where('name', $row['department'])->first();
            $po = StaffPosition::query()->where('position', $row['position'])->first();
            $dorm = Dorm::query()->where('code', $row['dorm_code'])->first();
            $id_card = $row['id_card'];
            $staff = Staff::query()->where('id_card', $id_card)->first();
            if ($staff) {
                $this->ignore++;
                return null;
            }
            $this->success++;
            return new Staff([
                'name' => $row['name'],
                'id_card' => $id_card,
                'card_num' => $row['card_num'],
                'sex' => $row['sex'] == '男' ? 1 : 2,
                'enroll_date' => $row['enroll_date'],
                'department_id' => optional($dept)->id,
                'staff_position_id' => optional($po)->id,
                'latest_in_date' => $row['in_date'],
                'dorm_id' => optional($dorm)->id
            ]);
        } catch (Exception $exception) {
            $this->fail++;

        }

    }
}
